package com.aspirecn.auth.config.security;

import com.alibaba.druid.util.Base64;
import com.aspirecn.auth.config.OAuth2SecurityConfiguration;
import com.aspirecn.auth.exception.LoginException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCrypt;

import java.util.Collection;

/**
 * 用户登陆校验
 *
 * @author ch
 */
public class MyAuthenticationProvider implements AuthenticationProvider {
    private static  Logger logger = LoggerFactory.getLogger(MyAuthenticationProvider.class);
    private UserDetailsService userService;

    public MyAuthenticationProvider(UserDetailsService userService) {
        this.userService = userService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //前端传来的帐号密码都用base64 encode过，admin，admin444
        String username = authentication.getName();
        logger.info("username:{},password:{}",username,authentication.getCredentials());
        @SuppressWarnings("unused")
        Base64 base64 = new Base64();
        byte[] b = null;
        byte[] p = null;
        try {
            b = Base64.base64ToByteArray(username);
            p= Base64.base64ToByteArray((String) authentication.getCredentials());
        } catch (Exception e) {
            throw new LoginException("账号或密码错误!");
        }
        String usernameStr = new String(b);
        String passwordStr = new String(p);
        //String password = (String) authentication.getCredentials();
        UserDetails user = userService.loadUserByUsername(usernameStr);
        if (user == null) {
            throw new BadCredentialsException("Username not found.");
        }
        logger.info("password:{},user.getpassword():{}",passwordStr,user.getPassword());
        boolean checkpw = BCrypt.checkpw(passwordStr, user.getPassword());
        // 加密过程在这里体现
        if (!checkpw) {
            throw new LoginException("密码错误!");
        }

        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        return new UsernamePasswordAuthenticationToken(user, passwordStr, authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }

}
